package com.weige.redis.redis_demo.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 定义redisTemplate的配置
 */
@Configuration
public class RedisConfig {


    /**
     *  当yml中配置了reids数据源的基本信息，底层会自动构建好RedisConnectionFactory连接工厂
     * @param connectionFactory redis的连接工厂
     *                          通过方法入参形式，将容器中的RedisConnectionFactory注入到方法下
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(@Autowired RedisConnectionFactory connectionFactory){
        //定义模板对象
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        //设置序列化方式
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        //JsonObjectSerializer<Object> objectJsonObjectSerializer = new JsonObjectSerializer<>(Object.class);
        //替换原有的jdk序列化方式
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
//        redisTemplate.setValueSerializer(keySerializer);
//        redisTemplate.setHashValueSerializer(keySerializer);
        //设置工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        //初始化设置
        redisTemplate.afterPropertiesSet();
        return  redisTemplate;
    }



}
